var word = "";
var run = false;
var step = 20;
var morebase = step;
var seeMore = function() {
	$.ajax({
		type: "GET",
		url: "hospital_list.php",
		data: "key=" + encodeURI(word) + "&base=" + morebase,
		dataType: "xml",
		success: function(xml){
			morebase += step;
			if ($("hospital", xml).size() > 0)
			{
				var hospitalList = "";
				$("hospital", xml).each(function(){
					hospitalList += "<li class=\"hospital_list_component\"><div class=\"hospital_image\"><img src=\"" + $(this).find("image").text() + "\" /></div>" +
						"<div class=\"hospital_info\"><span class=\"name\">" + 
						$(this).find("name").text() + "</span><span class=\"address\">" + 
						$(this).find("address").text() + "</span><span class=\"phone\">" +
						$(this).find("phone").text() + "</span></div><div class=\"hospital_link\"><a href=\"hospital_process.php?id=" +
						$(this).find("id").text() + "\">선택하기</a></div></li>";
				});
				$("#hospital_list").append(hospitalList);
				if ($("more", xml).text() <= 0)
				{
					$("#hospital_see_more").remove();
				}
			}
		},
			error: function(x, e, er) {
				alert(e);
			}

	});
}
var search = function() {
	if (!run) return;
	if ($("#hospital_search").attr("value").length < 1)
	{
		$("#hospital_list").html("");
		$("#hospital_see_more").remove();
	}
	if (word != $("#hospital_search").attr("value"))
	{
		morebase = step;
		word = $("#hospital_search").attr("value");

		$.ajax(
		{
			type: "GET",
			url: "hospital_list.php",
			data: "key=" + encodeURI(word) + "&base=0",
			dataType: "xml",
			success: function(xml) {
				$("#hospital_list").html("");
				$("#hospital_see_more").remove();
				if ($("hospital", xml).size() > 0)
				{
					var hospitalList = "";
					$("hospital", xml).each(function(){
						hospitalList += "<li class=\"hospital_list_component\"><div class=\"hospital_image\"><img src=\"" + $(this).find("image").text() + "\" /></div>" +
							"<div class=\"hospital_info\"><span class=\"name\">" + 
							$(this).find("name").text() + "</span><span class=\"address\">" + 
							$(this).find("address").text() + "</span><span class=\"phone\">" +
							$(this).find("phone").text() + "</span></div><div class=\"hospital_link\"><a href=\"hospital_process.php?id=" +
							$(this).find("id").text() + "\">선택하기</a></div></li>";
					});
					$("#hospital_list").append(hospitalList);
					if ($("more", xml).text() > 0)
					{
						$("#hospital_list").after("<div id=\"hospital_see_more\">더보기</div>");
						$("#hospital_see_more").click(seeMore);
					}
				}
			},
			error: function(x, e, er) {
				alert(e);
			}
		});
	}
	if (run)
	{
		setTimeout(search, 50);
	}
}
$(document).ready(function(){
	$("#hospital_search_form").submit(function(){ return false; });
	$("#hospital_search").focus(function(){ run = true; search(); });
	$("#hospital_search").blur(function(){ run = false; });
});
